;
(function() {

  new Vue({
    el: '#business-details',
    data: {
      tabData:[
        {'name':'线索详情', disabled: true},
        {'name':'跟进记录', disabled: true},
        {'name':'初步意向', disabled: true},
        // {'name':'访客单', disabled: true},
      ],
			tabSelectedName: '',
      tabSelectedIndex:0,
      data: {
        'themeInfo': {},
        'zlfInfo': {}
      },
      followList: [],
      closeReason: [],
      closeReasonObj: {
        'closeReasonCode': null,
        'closeReasonValue': null,
        'closeDescription': null
      },
      loadBuinessMesModule: true,
      loadFollowModule: false,
      loadInitIntentModule:false,
      loadFileModule:false,
      quanxian: window.localStorage.getItem('permissions'),
      businessId: hlUrlUtil.GetQueryString('businessId') || '1',
      isShowBusinessLayer: false,
      isScroll: false,
      sortName: '#',
      sortFlag: '#',
      lefthover: 0,
      tophover: 0,
      texthover: false,
      textLong: '',
      selfhover:false,
      yxFlag: false,
      editYxFlag: false,
      editYxIndex: -1,
      addYxIndex: 0,
      bounced: {
        unitFlag: false,
        wpFlag: false
      },
      unitData: [],
      wpData: [],
      // 选定项目下的原始单元及工位数据
      projects: {
        list: [],
        builddata: [],
        floorsdata: [],
        unitdata: [],
        stWpdata: [],
        id: null,
        projectName: null,
        buildingId: null,
        floorId: null,
        unitId: null
      },
      // 已选过的单元及工位数据
      projectInfo: {
        units: [],
        wpdata: [],
      },
      getname: {
        buildname: null,
        unitname: null,
        floorname: null,
        stop_acreage: null
      },
      // 新增意向数据
      addWillData: {
        type: {
          list: [{
            name: '整租',
            type: 'ER'
          }, {
            name: '工位',
            type: 'WR'
          }],
          active: 'ER'
        },
        acreage: [],
        st_count: null,
        wp_count: null,
        project_id: null,
        project_name: null
      },
      // 意向信息列表数据
      willsList: [],
      // 意向信息列表中确定添加的单元及工位数据
      willsConfirmedInfoList: [{
        'unitData': [],
        'wpData': []
      }],
      showFlag: true,
      beginTime:'',
      endTime:'',
			//获取需求面积
			intentAreaData: [],
			//访客单
      visitorFormInfo: [],
      
      attachmentsList:[]

    },
    filters: {
      formatUndefined: function(item) {
        if (!item) return '--'
        return item
      },
      max8lenOff(item) {
        if (!item) return '--'
        return item.length > 8 ? item.substr(0, 8) + '...' : item
      },
      formatFollowUpType: function(item) {
        if (!item) return '--'
        return hlCodeConvert.businessFollowUpType(item)
      },
      formatIntentLevel: function(item) {
        if (!item) return '--'
        return hlCodeConvert.businessFollowIntentLevel(item)
      },
      formatYYYYMMddHHmmss: function(item) {
        if (!item) return '--'
        return hlDateUtil.formatUTCDate(item)
      },
      formatDate: function(time) {
        if (time === undefined) return '--'
        return hlDateUtil.formatUTCDate(time, 'yyyy-MM-dd')
      },
      formatNum: function(item) {
        if (item === undefined) return '--'
        return hlNumberUtil.formatNum(item);
      },
    },
    computed: {
      unitList() {
        let result = [];
        if (this.data.intentType == 'ER') {
          let data = this.data.projectInfo.units;
          if (!data.length) return [];
          let buildinglist = hlArrayUtil.removeRepeat(data, 'buildingId')
          buildinglist.map(item => {
            result.push({
              projectName: this.data.projectInfo.projectName,
              projectId: this.data.projectInfo.projectId,
              buildingName: item.buildingName,
              buildingId: item.buildingId,
              floor: item.floorNum,
              floorId: item.floorId,
              children: []
            })
          })
          data.map(item => {
            result.map(item0 => {
              if (item.floorId == item0.floorId) {
                item0.children.push({
                  unitName: item.unitName,
                  unitId: item.unitId,
                  acreage: item.unitAcreage
                })
              }
            })
          })
        }
        return result
      },
      wplist() {
        let result = [];
        if (this.data.intentType == 'WR') {
          let data = this.data.projectInfo.wps;
          if (!data.length) return [];
          let buildinglist = hlArrayUtil.removeRepeat(data, 'unitId')
          buildinglist.map(item => {
            result.push({
              projectName: this.data.projectInfo.projectName,
              projectId: this.data.projectInfo.projectId,
              buildingName: item.buildingName,
              buildingId: item.buildingId,
              floor: item.floorNum,
              floorNum: item.floorNum,
              floorId: item.floorId,
              unitId: item.unitId,
              unitName: item.unitName,
              children: []
            })
          })
          data.map(item => {
            result.map(item0 => {
              if (item.unitId == item0.unitId) {
                item0.children.push({
                  wpName: item.wpName,
                  wpId: item.wpId
                })
              }
            })
          })
        }
        return result
      },
      stlist() {
        let result = [];
        if (this.data.projectInfo.stops.length) {
          let data = this.data.projectInfo.stops;
          if (!data.length) return [];
          let buildinglist = hlArrayUtil.removeRepeat(data, 'unitId')
          buildinglist.map(item => {
            result.push({
              projectName: this.data.projectInfo.projectName,
              projectId: this.data.projectInfo.projectId,
              buildingName: item.buildingName,
              buildingId: item.buildingId,
              floor: item.floorNum,
              floorId: item.floorId,
              unitId: item.unitId,
              unitName: item.unitName,
              children: []
            })
          })
          data.map(item => {
            result.map(item0 => {
              if (item.unitId == item0.unitId) {
                item0.children.push({
                  stopName: item.stopName,
                  stopId: item.stopId
                })
              }
            })
          })
        }
        return result
      },
      stCount() {
        let count = 0;
        if (this.stlist.length) {
          this.stlist.map(item => {
            count += item.children.length
          })
        }
        return count
      },
      wpCount() {
        let count = 0;
        if (this.wplist.length) {
          this.wplist.map(item => {
            count += item.children.length
          })
        }
        return count
      }
    },
    created() {
      var origin = hlUrlUtil.GetQueryString('origin');
      if (origin == 'gj') {
        this.loadFollowModule = true;
        this.loadBuinessMesModule = false
        this.tabSelectedIndex = 1
      }
			let power = JSON.parse(window.localStorage.getItem('permissions'))
			if (power.indexOf('c353') > -1) {
				this.tabData = [
					{'name':'线索详情', disabled: true},
					{'name':'跟进记录', disabled: true},
					{'name':'初步意向', disabled: true},
					{'name':'访客单', disabled: true},
				]	
			}
			this.intentAreaDataGet()
    },
    methods: {
		//金额保留俩位小数
		tofixed2 () {
			
		},
      previewImage: function(url) {
        var imageExt = ['jpg', 'jpeg', 'png', 'JPG', 'JPEG', 'PNG'];
        var pdfExt = ['pdf', 'PDF'];
        var officeExt = ['docx', 'doc', 'xlsx', 'xls', 'xlt']
        var imageFlag = false;
        var pdfFlag = false;
        var officeFlag = false;

        imageExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) imageFlag = true;
        })

        if (imageFlag) {
          $.imageShow([url])
          return
        }
        pdfExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) pdfFlag = true;
        })
        if (pdfFlag) {
          $.previewPDF(url)
          return
        }

        officeExt.forEach((e, i) => {
          if (url.indexOf(e) !== -1) officeFlag = true
        })
        if (officeFlag) {
          $.previewOffice(url)
          return
        }
        hl.toast('暂不支持该格式')
      },
			//取消关联
			visitor_form_info_cancel (item) {
				hllayer.confirm1('确认取消关联？', () => {
				  hlhttp.put({
				  	url: 'visitor_form_info/cancel_relate',
				  	data: {id: item.id},
				  	success: (data) => {
				  		this.visitor_form_info()
				  	}
				  })
				})
			},
			//访客单
			visitor_form_info () {
				hlhttp.get({
					url: 'visitor_form_info/by_ref_cstmr',
					data: {ref_cstmr_id: this.businessId, ref_cstmr_type: 'XS'},
					success: (data) => {
						this.visitorFormInfo = data;
					}
				})
			},
			//需求面积
			intentAreaDataGet () {
			  var that = this
			  hlhttp.get({
			    url: 'configure/dict',
			    data: {
			      module_code: 'ZHSH',
			      config_name: 'ZS_INTENT_AREA'
			    },
			    success: (data) => {
			      data.map(item => {
			        item.name = item.dictName
							item.code = item.dictCode
							if (item.status == 'Y') {
								that.intentAreaData.push(item)
							}
			      })
			    },
			  })
			},
			
      // 删除联系人
      delItemContacter() {
        hllayer.confirm('此操作不可逆转，确认删除此联系人吗?', () => {})
      },
      // 新建/编辑联系人
      addcontacter() {
        this.addcontacterbasis = true;
        this.isShowBusinessLayer = true
      },
      //显示hover
      hoverText(e, v) {
        var s = this.$refs.scrollLeft.scrollLeft;
        var l = e.srcElement.parentNode.offsetLeft - s ;
        var t = e.srcElement.parentNode.offsetTop + 20
        this.lefthover = l + 'px';
        this.tophover = t + 'px';
        this.texthover = true;
        this.textLong = v;
      },
      mouseleaveOut() {
        this.texthover = false;
      },
      getDetailsData: function() {
        var self = this;
        hlhttp.get({
          url: 'customer/biz_oppt_info',
          data: {
            'sj_id': self.businessId
          },
          success: function(data) {
            if(data.attachments.length){
              self.tabData.push({'name':'相关文件', disabled: true})
            }
            self.attachmentsList = data.attachments
            self.data = data;
            loginPrem.loginList()
          }
        })
      },
      handleSelectedTab: function(val, i) {
        const {name,isDisabled} = val;
				
				this.tabSelectedName = name;

        if (name == '线索详情') {
          this.loadBuinessMesModule = true
          this.loadFollowModule = false
          this.loadInitIntentModule = false
          this.loadFileModule = false
        }
        if (name == '跟进记录') {
          this.loadBuinessMesModule = false
          this.loadFollowModule = true
          this.loadInitIntentModule = false
          this.loadFileModule = false
        }
        if (name == '初步意向') {
          this.loadBuinessMesModule = false
          this.loadFollowModule = false
          this.loadInitIntentModule = true
          this.loadFileModule = false
          this.getintentList();
        }
        if (name == '相关文件') {
          this.loadBuinessMesModule = false
          this.loadFollowModule = false
          this.loadInitIntentModule = false
          this.loadFileModule = true
        }
				
				if (name == '访客单') {
				  this.loadBuinessMesModule = false
				  this.loadFollowModule = false
          this.loadInitIntentModule = false
          this.loadFileModule = false
					this.visitor_form_info()
				}

      },
      // 编辑线索
      editBusiness: function() {
        var self = this;
        hlUrlUtil.goTo('businessEdit', {
          businessId: self.businessId,
          ddtab: true
        }, true)
      },
      // 作废合同
      invalidContract: function() {
        var self = this;
        hllayer.confirm1('此操作不可逆转，确定作废变更单吗？', function() {
          hlhttp.put({
            url: 'contract_alter/_cancel',
            data: {
              "alter_id": self.alterId
            },
            success: function(data) {
              self.getData()
            }
          })
        })
      },
      getFollowListData() {
        var self = this;
        hlhttp.get({
          url: 'customer/biz_oppt_followup_records',
          data: {
            'sj_id': self.businessId,
            'columns': self.sortName,
            'orders': self.sortFlag
          },
          success: function(data) {
            self.followList = data;
          }
        })
      },
      sortByRecordTime() {
        this.sortName = 'CFRT'
        if (this.sortFlag == 'ASC') {
          this.sortFlag = 'DESC'
          $('.bt-icon').removeClass('icon-Gm-sort-ascending').addClass('icon-Gm-sort-descending')
        } else {
          this.sortFlag = 'ASC'
          $('.bt-icon').removeClass('icon-Gm-sort-descending icon-Gm-sort-default').addClass('icon-Gm-sort-ascending')
        }
        this.getFollowListData()
      },
      getCloseReason() {
        var self = this;
        hlhttp.get({
          url: 'configure/dict',
          data: {
            'module_code': 'ZHSH0SHJI',
            'config_name': 'SJ_CLOSE_REASON'
          },
          success: function(data) {
            self.closeReason = data
            self.closeReasonObj.closeReasonCode = data[0]['dictCode']
            self.closeReasonObj.closeReasonValue = data[0]['dictName']
          }
        })
      },
      selectCloseReason(code, val) {
        this.closeReasonObj.closeReasonCode = code;
        this.closeReasonObj.closeReasonValue = val;
      },
      // 跟进线索
      followBusiness() {
        var self = this
        var page = hlUrlUtil.GetQueryString('page')
        hlUrlUtil.goTo('businessGJ', {
          businessId: self.businessId,
          page: page,
          ddtab: true
        }, true)
      },
      // 转为客户
      convertToCustomer() {
        var RENT_BUSINESS_CUSTOMER = {
          'customerType': this.data.zlfInfo.customerType,
          'customerName': this.data.zlfInfo.customerName,
          'industryCode': this.data.zlfInfo.industryCode,
          'industryName': this.data.zlfInfo.industryName,
          'idcode': this.data.zlfInfo.idcode,
          channelCategoryCode: this.data.themeInfo.channelCategoryCode,
          channelCategoryValue: this.data.themeInfo.channelCategoryValue,
          'channelNameCode': this.data.themeInfo.channelNameCode,
          'channelNameValue': this.data.themeInfo.channelNameValue,
          'email': this.data.zlfInfo.email,
          'lperson': this.data.zlfInfo.lperson,
          'phone': this.data.zlfInfo.phone,
					address: this.data.zlfInfo.customerAddress,
        }
        window.sessionStorage.setItem('RENT_BUSINESS_CUSTOMER', JSON.stringify(RENT_BUSINESS_CUSTOMER))
        hlUrlUtil.goTo('createCm', {
          businessId: this.businessId,
          isFromBusinessDetails: 'Y',
          ddtab: true
        }, false)
      },
      // 关闭线索
      closeBusiness() {
        this.isShowBusinessLayer = true;
      },
      showScroll() {
        this.isScroll = true;
      },
      hideScroll() {
        this.isScroll = false;
      },
      cancelCloseBusinessLayer() {
        this.isShowBusinessLayer = false;
      },
      confirmCloseBusiness() {
        var self = this;
        hlhttp.put({
          url: 'customer/biz_oppt_close',
          data: {
            'sj_id': self.businessId,
            'close_reason_code': self.closeReasonObj.closeReasonCode,
            'close_reason_value': self.closeReasonObj.closeReasonValue,
            'close_description': self.closeReasonObj.closeDescription || '#'
          },
          success: function(data) {
            hl.toast('线索已成功关闭')
            self.getDetailsData()
            self.isShowBusinessLayer = false;
          }
        })
      },

      // 新增初步意向

      // 获取意向列表
      getintentList() {
        var that = this
        hlhttp.get({
          url: 'intent/initials',
          data: {
            customer_or_sj_id: this.businessId,
            page_source: 'OPB'
          },
          success: function(data) {
            that.willsList = data
            that.willsList.forEach(item => {
              if (item.projectInfo.wps.length) {
                var map = {},
                  dest = [];
                for (var i = 0; i < item.projectInfo.wps.length; i++) {
                  var ai = item.projectInfo.wps[i];
                  if (!map[ai.unitId]) {
                    var a = {
                      building_id: ai.buildingId,
                      building_name: ai.buildingName,
                      floor_id: ai.floorId,
                      floor_num: ai.floorNum,
                      positions: [],
                      unit_id: ai.unitId,
                      unit_name: ai.unitName,
                      wp_acreage: ai.wpAcreage,
                    }
                    let b = {
                      position_id: '',
                      position_name: '',
                    }
                    b.position_id = ai.wpId
                    b.position_name = ai.wpName
                    a.positions.push(b)
                    dest.push(a)
                    map[ai.unitId] = ai;
                  } else {
                    for (var j = 0; j < dest.length; j++) {
                      var dj = dest[j];
                      if (dj.unit_id == ai.unitId) {
                        let c = {
                          position_id: '',
                          position_name: '',
                        }
                        c.position_id = ai.wpId
                        c.position_name = ai.wpName
                        dj.positions.push(c)
                        break;
                      }
                    }
                  }
                }
                item.positionsList = dest
              }
              item.projectInfo.units = JSON.parse(JSON.stringify(item.projectInfo.units).replace(/buildingId/g, "building_id"));
              item.projectInfo.units = JSON.parse(JSON.stringify(item.projectInfo.units).replace(/buildingName/g, "building_name"));
              item.projectInfo.units = JSON.parse(JSON.stringify(item.projectInfo.units).replace(/floorId/g, "floor_id"));
              item.projectInfo.units = JSON.parse(JSON.stringify(item.projectInfo.units).replace(/floorNum/g, "floor_num"));
              item.projectInfo.units = JSON.parse(JSON.stringify(item.projectInfo.units).replace(/unitId/g, "unit_id"));
              item.projectInfo.units = JSON.parse(JSON.stringify(item.projectInfo.units).replace(/unitName/g, "unit_name"));
              item.projectInfo.units = JSON.parse(JSON.stringify(item.projectInfo.units).replace(/unitAcreage/g, "unit_acreage"));
            })
          }
        })
      },



      //初步意向
      //获取签约项目
      getProjects: function() {
        var self = this;
        hlhttp.get({
          url: 'user/projects',
          success: function(data) {
            self.projects.list = data;
          }
        })
      },
      getProjectsId: function(id, name) {
        var self = this;
        self.projects.id = id;
        self.projects.projectName = name;
        self.addWillData.project_id = id;
        self.addWillData.project_name = name;
      },
      //获取楼宇  n == 1 单元  n == 2 工位
      getBuildings: function(n) {

        this.projects.id = this.addWillData.project_id
        if (!this.addWillData.project_id) {
          hl.toast('请先选择意向项目')
          return false;
        }
        var self = this;
        if (n == 1) this.bounced.unitFlag = true;
        if (n == 2) this.bounced.wpFlag = true;

        hlhttp.get({
          url: 'project/buildings',
          data: {
            project_id: self.projects.id
          },
          success: function(res) {
            self.projects.builddata = res
          }
        })
      },
      //获取楼宇id:
      getBuildId: function(id, name) {
        this.projects.buildingId = id;
        this.getname.buildname = name;
        this.projects.stWpdata = [];
        $('.floor-select span, .unit-select span, .building-select span').text('请选择')
        var _this = this;
        hlhttp.get({
          url: 'building/floors',
          data: {
            project_id: _this.projects.id,
            building_id: id,
          },
          success: function(res) {
            _this.projects.unitdata = [];
            if (res.length === 0) {
              hl.toast('暂无楼层，请重新选择')
              return false
            }
            _this.projects.floorsdata = res
          }
        })
      },
      //查询
      queryUnit: function() {
        if (!this.projects.floorId) return;
        var _this = this;
        hlhttp.get({
          url: 'floor/units',
          data: {
            project_id: _this.projects.id,
            floor_id: _this.projects.floorId,
            building_id: _this.projects.buildingId
          },
          success: function(res) {
            if (res.length === 0) {
              hl.toast('暂无单元，请重新选择')
              return false
            }
            _this.projects.unitdata = res
          }
        })
      },
      //获取楼层下的单元
      getUnits: function(id, name) {
        this.projects.floorId = id;
        this.getname.floorname = name;
        var _this = this;
        this.projects.unitdata = [];
        $('.last-unit span').removeClass('activeNot active')
        $('.unit-select span').text('请选择')
        hlhttp.get({
          url: 'floor/units',
          data: {
            project_id: _this.projects.id,
            floor_id: _this.projects.floorId,
            building_id: _this.projects.buildingId
          },
          success: function(res) {
            if (res.length === 0) {
              hl.toast('暂无单元，请重新选择')
              return false
            }
            _this.projects.unitdata = res
            setTimeout(function() {
              _this.selectUnit()
            }, 200);
          }
        })
      },
      //勾选单元（显示）
      selectUnit: function() {
        var _this = this;
        // 原已添加过的单元灰色标记
        for (var i = 0; i < _this.projectInfo.units.length; i++) {
          $('.unit-active span').each(function(index, el) {
            if ($(el).attr('data-unitid') == _this.projectInfo.units[i].unit_id) {
              $(el).addClass('activeNot')
            }
          });
        }
      },
      //选中取消单元
      selUnit: function(e, i, id) {
        var data = this.projects.unitdata;

        if ($(e.srcElement).hasClass('activeNot')) {
          hl.toast('无法操作选择过的单元')
          return
        }
        // 选中单元
        if ($(e.srcElement).hasClass('active') === false) {
          $(e.srcElement).addClass('active')
          this.projectInfo.units.push({
            building_id: data[i].buildingId,
            building_name: this.getname.buildname,
            floor_id: data[i].floorId,
            floor_num: this.getname.floorname,
            unit_id: data[i].unitId,
            unit_name: data[i].unitName,
            unit_acreage: String(data[i].acreage)
          })
          return false;
        }
        // 取消单元
        if ($(e.srcElement).hasClass('active')) {
          $(e.srcElement).removeClass('active')
          for (var j = 0; j < this.projectInfo.units.length; j++) {
            if (this.projectInfo.units[j].unit_id == id) {
              this.projectInfo.units.splice(j, 1)
            }
          }
          return false;
        }
      },
      // 确认添加单元或者工位
      confirmAddUnitsOrWp: function(n) {
        // 添加单元
        if (n == 1) {
          this.unitData = JSON.parse(JSON.stringify(this.projectInfo.units));
          this.bounced.unitFlag = false;
          this.clearOriginalProMes()
        }
        // 添加工位
        if (n == 2) {
          this.wpData = JSON.parse(JSON.stringify(this.projectInfo.wpdata));
          this.bounced.wpFlag = false;
          this.clearOriginalProMes()
        }
      },
      // 关闭单元弹窗
      closeAddUnitPop: function() {
        this.bounced.unitFlag = false;
        this.clearOriginalProMes()
      },
      // 关闭工位弹窗
      closeAddwpPop: function() {
        this.bounced.wpFlag = false;
        this.clearOriginalProMes()
      },
      //获取车位工位单元
      getStWpUnitsList: function(id, name) {
        var _this = this;
        this.projects.floorId = id;
        this.getname.floorname = name;
        $('.unit-select span').text('请选择')
        this.projects.unitdata = [];
        this.projects.stWpdata = []
        hlhttp.get({
          url: 'floor/units',
          data: {
            project_id: _this.projects.id, //项目ID
            floor_id: id, //楼层ID
            building_id: _this.projects.buildingId
          },
          success: function(res) {
            _this.projects.unitdata = res;
          }
        })
      },
      //获取工位
      getWp: function(id, name, index) {
        var _this = this;
        this.projects.unitId = id;
        this.getname.unitname = name;
        this.uIndex = index;
        $('.st-unit span').removeClass('activeNot active')
        hlhttp.get({
          url: 'units/positions',
          data: {
            unit_id: id
          },
          success: function(res) {
            _this.projects.stWpdata = res;
            setTimeout(function() {
              _this.selectUnitWp()
            }, 200);
          }
        })
      },
      // 标记已选择过的工位
      selectUnitWp: function() {
        var _this = this;
        for (var w = 0; w < this.projectInfo.wpdata.length; w++) {
          var wpAct = this.projectInfo.wpdata[w].positions;
          $('.wp-list span').each(function(index, el) {
            for (var wp = 0; wp < wpAct.length; wp++) {
              if ($(el).attr('data-posId') == wpAct[wp].position_id) {
                $(el).addClass('activeNot')
              }
            }
          });
        }
      },
      // 勾选工位
      selectWp: function(e, i, id, name) {
        var data = this.projects.unitdata;

        if ($(e.srcElement).hasClass('activeNot')) {
          hl.toast('无法操作选择过的工位')
          return
        }

        // 选中工位
        if (!$(e.srcElement).hasClass('active')) {
          $(e.srcElement).addClass('active')

          if (!this.projectInfo.wpdata.length) {
            this.projectInfo.wpdata.push({
              building_id: this.projects.buildingId,
              building_name: this.getname.buildname,
              floor_id: this.projects.floorId,
              floor_num: this.getname.floorname,
              unit_id: this.projects.unitId,
              unit_name: this.getname.unitname,
              wp_acreage: this.addWillData.wp_count,
              positions: [{
                position_id: id, //车位ID
                position_name: name
              }],
            })
          } else {
            var flag = false;
            index = null;
            for (var j = 0; j < this.projectInfo.wpdata.length; j++) {
              if (this.projectInfo.wpdata[j].unit_id == this.projects.unitId) {
                index = j;
                flag = 1;
                break;
              } else {
                index = j;
                flag = 2;
              }
            }
            if (flag == 1) {

              this.projectInfo.wpdata[index].positions.push({
                position_id: id,
                position_name: name
              })
            }
            if (flag == 2) {

              this.projectInfo.wpdata.push({
                building_id: this.projects.buildingId,
                building_name: this.getname.buildname,
                floor_id: this.projects.floorId,
                floor_num: this.getname.floorname,
                unit_id: this.projects.unitId,
                unit_name: this.getname.unitname,
                wp_acreage: this.addWillData.wp_count,
                positions: [{
                  position_id: id,
                  position_name: name
                }],
              })
            }
          }

          return false;
        }
        // 取消工位
        if ($(e.srcElement).hasClass('active')) {
          $(e.srcElement).removeClass('active')

          var unitid = this.projects.unitId
          var newdata = this.projectInfo.wpdata.filter(function(item) {
            return item.unit_id == unitid;
          })
          for (var m = 0; m < newdata[0].positions.length; m++) {
            if (newdata[0].positions[m].position_id == id) {
              newdata[0].positions.splice(m, 1)
              break;
            }
          }
          this.projectInfo.wpdata.forEach((item, index, object) => {
            if (!item.positions.length) {
              object.splice(index, 1);
            }
          })

          return false;
        }
      },
      //删除单元
      deleteUnit: function(i) {
        this.unitData.splice(i, 1)
        this.projectInfo.units.splice(i, 1)
      },
      //删除已选的工位
      delwp: function(item, index0, index) {
        // this.wpData[i].positions.splice(n, 1)
        // if (!this.wpData[i].positions.length) {
        //   this.wpData.splice(i, 1)
        // }
        item.positions.splice(index0, 1)
        if (!item.positions.length) {
          this.wpData.splice(index, 1)
        }
        this.projectInfo.wpdata = JSON.parse(JSON.stringify(this.wpData));
      },
      // 清空原选择的单元或者工位信息(但未确认添加过，即原始数据)
      clearOriginalProMes: function(n) {
        var self = this;
        var clear = function() {
          self.projectInfo.units = JSON.parse(JSON.stringify(self.unitData))
          self.projectInfo.wpdata = JSON.parse(JSON.stringify(self.wpData))
          self.projects.unitdata = [];
          self.projects.floorsdata = [];
          self.projects.stWpdata = [];
          self.projects.buildingId = null;
          self.projects.unitId = null;
          // self.projectInfo.wpdata = JSON.parse(JSON.stringify(self.wpData));
          self.getname = {
            buildname: null,
            unitname: null,
            floorname: null,
            stop_acreage: null
          };
          $('.floor-select span, .unit-select span, .building-select span').text('请选择')
        }
        clear()
      },
      // 清空原添加过的单元或者工位信息
      clearAddedMes: function() {
        var data = {
          units: [],
          wpdata: []
        }
        this.projectInfo = data;
      },
      // 添加意向
      addWill: function() {
        if (this.yxFlag === true) hl.toast('请先保存已添加的意向信息')
        if (this.yxFlag === false) {
          if (this.editYxFlag === false) {
            this.yxFlag = true
            this.beginTime = ''
            this.endTime = ''
            return false
          }
          if (this.editYxFlag === true) {
            hl.toast('请先取消或者保存先前编辑操作')
            return false
          }
        }
      },
      // 取消意向
      cancelWill: function() {
        var self = this;
        var data = {
          'type': {
            list: [{
              name: '整租',
              type: 'ER'
            }, {
              name: '工位',
              type: 'WR'
            }],
            active: 'ER'
          },
          'acreage': [],
          'st_count': null,
          'wp_count': null,
          'project_id': null,
          'project_name': null,
		  'budget_amount': null
        }
        self.$set(self.$data, 'addWillData', data)
        self.unitData = [];
        self.wpData = [];
        self.yxFlag = false;
        self.editYxFlag = false;
        self.editYxIndex = -1;
        self.clearOriginalProMes()
        self.clearAddedMes()
      },
      // 保存意向
      saveWill: function(type, willId) {
        var self = this;
        if (!self.validateYxMes()) {
          return false;
        }
        // 保存数据
        var YxData = function() {
					let area = self.addWillData.acreage.length ? self.addWillData.acreage[0] : '#'
          var data = {
            'page_source': 'OPB',
            'biz_id': self.businessId,
            'intent_id': willId,
            'project_id': self.addWillData.project_id,
            'project_name': self.addWillData.project_name,
            'intent_type': self.addWillData.type.active,
            'intent_acreage': self.addWillData.type.active == 'ER' ? area : self.addWillData.wp_count || '#',
            'intent_parking_num': self.addWillData.st_count || '#',
			budget_amount: self.addWillData.budget_amount ? self.addWillData.budget_amount.toFixed(4) : '#',
            'intent_start_date': self.beginTime,
            'intent_end_date': self.endTime,
            'customer_id': "#",
          }

          var willArr = [];
          var wps = [];
          var wpsplus = [];

          self.projectInfo.units = JSON.parse(JSON.stringify(self.projectInfo.units).replace(/buildingId/g, "building_id"));
          self.projectInfo.units = JSON.parse(JSON.stringify(self.projectInfo.units).replace(/buildingName/g, "building_name"));
          self.projectInfo.units = JSON.parse(JSON.stringify(self.projectInfo.units).replace(/floorId/g, "floor_id"));
          self.projectInfo.units = JSON.parse(JSON.stringify(self.projectInfo.units).replace(/floorNum/g, "floor_num"));
          self.projectInfo.units = JSON.parse(JSON.stringify(self.projectInfo.units).replace(/unitId/g, "unit_id"));
          self.projectInfo.units = JSON.parse(JSON.stringify(self.projectInfo.units).replace(/unitName/g, "unit_name"));
          self.projectInfo.units = JSON.parse(JSON.stringify(self.projectInfo.units).replace(/unitAcreage/g, "unit_acreage"));

          self.projectInfo.units.forEach(item => {
            item.unit_acreage = String(item.unit_acreage)
          })

          if (data.intent_type === 'ER') {
            willArr = self.projectInfo.units;
            willArr.map(function(_item) {
              _item.positions = '#'
            })
            var units = JSON.stringify(willArr)
          }
          if (data.intent_type === 'WR') {
            wps = self.projectInfo.wpdata;
            wps.forEach(item => {
              item.positions.forEach(single => {
                wpsplus.push({
                  "building_id": item.building_id,
                  "building_name": item.building_name,
                  "floor_id": item.floor_id,
                  "floor_num": item.floor_num,
                  "unit_id": item.unit_id,
                  "unit_name": item.unit_name,
                  "wp_acreage": String(item.wp_acreage),
                  "wp_id": single.position_id,
                  "wp_name": single.position_name
                })
              })
            })
          }
          if (!wpsplus.length) {
            wpsplus = "#"
          }
          let project_Info = {
            'project_id': self.addWillData.project_id,
            'project_name': self.addWillData.project_name,
            'units': units || "#",
            'wps': JSON.stringify(wpsplus),
            'stops': JSON.stringify("#"),
          }
          data.project_info = JSON.stringify(project_Info)

          return data
        }
        var sendAddYxRequest = function() {
          hlhttp.post({
            url: 'intent/initial',
            data: YxData(),
            success: function(data) {
              hl.toast('保存成功')
              self.yxFlag = false
              self.cancelWill()
              self.getintentList()
            }
          })
        }
        var sendEditYxRequest = function() {
          hlhttp.put({
            url: 'intent/initial',
            data: YxData(),
            success: function(data) {
              hl.toast('编辑成功')
              self.editYxFlag = false;
              self.editYxIndex = -1;
              self.cancelWill()
              self.getintentList()
            }
          })
        }
        if (type === 'add') {
          sendAddYxRequest()
        }
        if (type === 'edit') {
          sendEditYxRequest()
        }
      },
      // 删除意向
      deleteWill: function(id) {
        hllayer.confirm('确认要删除该组意向吗?', () => {
          var self = this;
          hlhttp.delete({
            url: 'intent/initial?intent_id=' + id,
            data: {
              intent_id: id
            },
            success: function(data) {
              hl.toast('删除成功')
              self.getintentList()
            }
          })
        })
      },
      // 编辑意向
      editWill: function(i) {
        var self = this;
        if (self.editYxFlag === true) {
          hl.toast('请先取消或者保存先前编辑操作')
          return false
        }
        if (self.yxFlag === true) {
          hl.toast('请先取消或者保存先前新增操作')
          return false
        }

        self.editYxFlag = true;
        self.editYxIndex = i;
        // 基本信息
        self.addWillData.type = {
          list: [{
            name: '整租',
            type: 'ER'
          }, {
            name: '工位',
            type: 'WR'
          }],
          active: self.willsList[i].intentType
        }

        if (self.willsList[i].intentType == 'ER') {
					self.addWillData.acreage = [self.willsList[i].intentAcreage];
				}
        
        self.addWillData.st_count = self.willsList[i].intentParkingNum;
		self.addWillData.budget_amount = self.willsList[i].budgetAmount;
        self.addWillData.project_id = self.willsList[i].projectInfo.projectId;
        self.addWillData.project_name = self.willsList[i].projectInfo.projectName;
        // 单元工位信息
        self.unitData = self.willsList[i].projectInfo.units;
        self.projectInfo.units = JSON.parse(JSON.stringify(self.unitData))
        if (self.willsList[i].intentType == 'WR') {
					self.addWillData.wp_count = self.willsList[i].intentAcreage;
          self.wpData = self.willsList[i].positionsList;
          self.projectInfo.wpdata = JSON.parse(JSON.stringify(self.wpData))
        }
        // 项目信息
        // 时间
        setTimeout(function() {
          self.beginTime = hlDateUtil.formatUTCDate(self.willsList[i].intentStartDate, 'yyyy-MM-dd')
          self.endTime = hlDateUtil.formatUTCDate(self.willsList[i].intentEndDate, 'yyyy-MM-dd')
        }, 200)



      },
      // 选择意向类型
      selectYxType: function(type) {
        if (type == 'ER') {
          this.addWillData.type.active = 'ER'
        }
        if (type == 'WR') {
          this.addWillData.type.active = 'WR'
        }
      },
      // 验证意向信息
      validateYxMes: function() {
        var self = this;
        if (!self.beginTime) {
          hl.toast('请选择开始时间')
          return false
        }
        if (!self.endTime) {
          hl.toast('请选择结束时间')
          return false
        }
        if (self.addWillData.type.active == 'ER') {
          if (!self.addWillData.acreage) {
            hl.toast('请填写需求面积')
            return false
          }
        }
        if (self.addWillData.type.active == 'WR') {
          if (!self.addWillData.wp_count) {
            hl.toast('请填写需求个数')
            return false
          }
        }
        if (!self.addWillData.project_id) {
          hl.toast('请选择项目')
          return false
        }
        if (self.addWillData.type.active == 'ER') {
          if (self.projectInfo.units.length === 0) {
            hl.toast('请选择意向单元')
            return false
          }
        }
        if (self.addWillData.type.active == 'WR') {
          if (self.projectInfo.wpdata.length === 0) {
            hl.toast('请选择意向工位')
            return false
          }
        }
        return true;
      },
    },
    mounted: function() {
      hlSelectUi()
      this.getDetailsData()
      this.getFollowListData()
      this.getCloseReason()
      this.getProjects()
    }
  })
}())
